package com.bn.commerce.pricing.calculators;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import com.bn.commerce.order.BnGiftCardCommerceItemImpl;

import atg.commerce.order.CommerceItem;
import atg.commerce.pricing.ItemListPriceCalculator;
import atg.commerce.pricing.ItemPriceInfo;
import atg.commerce.pricing.PricingAdjustment;
import atg.commerce.pricing.PricingException;
import atg.repository.RepositoryItem;

/**
 * A calculator which sets the user entered price to itemPriceInfo object.
 *
 * @author ampuser
 *
 */
public class BNItemGiftCardAmountCalculator extends ItemListPriceCalculator {

	/**
	 * Method sets the the user entered price into the itemPriceInfo object.
	 */
	public void priceItem(ItemPriceInfo pPriceQuote, CommerceItem pItem, RepositoryItem pPricingModel, Locale pLocale, RepositoryItem pProfile, Map pExtraParameters) throws PricingException {

		double giftCardAmount = 0d;
		double totalPrice = 0d;
		double oldAmount = 0d;
		double adjustAmount = 0d;
		PricingAdjustment adjustment = null;

		if (pItem instanceof BnGiftCardCommerceItemImpl) {
			{
				if (isLoggingDebug()) {
					logDebug("Performing Pricing for GiftCard : ");
				}
				BnGiftCardCommerceItemImpl item = (BnGiftCardCommerceItemImpl) pItem;
				giftCardAmount = item.getUserEnteredAmount();
				long Qty = item.getQuantity();
				Double totalAmt = giftCardAmount * Qty;
				if (isLoggingDebug()) {
					logDebug("User entered price : " + totalAmt);
				}
				totalPrice = getPricingTools().round(totalAmt);
				oldAmount = pPriceQuote.getAmount();
				pPriceQuote.setListPrice(totalPrice);
				pPriceQuote.setAmount(totalPrice);
				pPriceQuote.setRawTotalPrice(totalPrice);
				adjustAmount = totalPrice - oldAmount;

				List detailsList = pPriceQuote.getCurrentPriceDetails();
				if(detailsList == null)
				detailsList = new ArrayList(1);
				List newDetails = getPricingTools().getDetailedItemPriceTools().createInitialDetailedItemPriceInfos(totalPrice, pPriceQuote, pItem, pPricingModel, pLocale, pProfile, pExtraParameters, "GiftCard Price Adjustment");
				detailsList.addAll(newDetails);


				adjustment = new PricingAdjustment("GiftCard Price Adjustment", pPricingModel, getPricingTools().round(adjustAmount), pItem.getQuantity());
				pPriceQuote.getAdjustments().add(adjustment);

				List adjustments = pPriceQuote.getAdjustments();
				if(adjustments.size() > 0)
				adjustments.clear();
				adjustments.add(adjustment);
			}
		}
	}
}
